package cn.tedu.file;

import java.io.*;

public class TestCopy {
    public static void main(String[] args) {
        File source = new File("E:\\dgtest");
        File target = new File("E:\\dgtest1");
        if(!target.exists()){
            target.mkdir();
        }
        try {
            copyFiles(source,target);
        }catch (Exception e){
            System.err.println(e.getMessage());
        }
    }

    private static void copyFiles(File source, File target) throws FileNotFoundException {
        if(!source.exists()){
            throw new FileNotFoundException("没有找到资源");
        }
        File[] sourceFiles = source.listFiles();
        for (File oldFile : sourceFiles){
            String name = oldFile.getName();
            if(oldFile.isDirectory()){
                File newFile = new File(target+"\\"+name);
                System.out.println(newFile.getPath());
                newFile.mkdir();
                copyFiles(oldFile,newFile);
            }else{
                try (
                        FileInputStream fis = new FileInputStream(oldFile);
                        FileOutputStream fos = new FileOutputStream(target+"\\"+name);
                        ){
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                byte[] bytes = new byte[1024];
                int size = 0;
                    while ((size = bis.read(bytes))!=-1){
                        bos.write(bytes,0,size);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
    }
}
